package com.ship.common.business.mapping;

import com.alibaba.fastjson2.JSONArray;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.base.BaseBean;
import com.ship.common.core.base.Constant;
import com.ship.common.core.exception.SystemException;
import com.ship.common.core.mapping.Label;
import com.ship.common.core.utils.ConstantUtil;
import com.ship.common.core.utils.SpringUtil;
import com.ship.common.core.utils.StringUtil;
import com.ship.system.api.RemoteCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Class.forName;

/**
/**
 * @author 31463
 */
@Component
@Slf4j
public class EnumContentProvider extends ContentProvider{

	@Autowired
	private RemoteCommonService remoteCommonService;

	@Autowired
	private SpringUtil springUtil;

	private Map<String, Map<String, String > > map = new LinkedHashMap<String, Map<String, String >>();

	public static final String MULTI_SELECT_SPLITER = ",";

	public static final String MULTI_SELECT_SPLITER_EXCEL = "/";

	public boolean contains(String enumName) {
		if(map.containsKey(enumName)) {
			return true;
		}
		@SuppressWarnings("deprecation")
		List<Constant> list = new ArrayList<Constant>(remoteCommonService.listByType(enumName));
		if(list.size()  == 0) {
			return false;
		}
		Map<String, String > enumContent = new LinkedHashMap<String, String>();
		for (Constant constant : list) {
			enumContent.put(String.valueOf(constant.getConstValue()), constant.getConstLabel());
		}
		map.put(enumName, enumContent);
		return true;
	}

	public Map<String, String > getEnumContent(String enumName){
		if(contains(enumName)) {
			return map.get(enumName);
		}
		throw new SystemException("枚举内容【" + enumName + "】不存在");
	}

	public Object getValue(String label, Object currentValue, Object root, Field field, String expression) throws SystemException {
		if(currentValue == null || "".equals(currentValue)) {
			return null;
		}
		if(currentValue instanceof Integer || currentValue.toString().replaceAll(",", "").matches("^[1-9]\\d*$")) {
			return currentValue;
		}
		Label l = field.getAnnotation(Label.class);
		if(l.multiSelect()) {
			String result = "";
			for(String name : ((String)currentValue).split(MULTI_SELECT_SPLITER_EXCEL)) {
				String value = getValueByLabel(name, l.enumContent());
				if(value != null) {
					result += MULTI_SELECT_SPLITER + value;
				}else {
					throw new SystemException("内容[" + name + "]填写错误，请检查有效性 ");
				}
			}
			return result.substring(1);
		}
		try {
			return Integer.parseInt(getValueByLabel(currentValue.toString(), l.enumContent()));
		} catch (Exception e) {
			throw new SystemException("内容填写错误，请检查有效性");
		}
	}

	private String getValueByLabel(String label, String enumName) {
		Map<String, String> map = getEnumContent(enumName);
		if(map == null) {
			throw new SystemException("枚举内容配置错误：枚举【" + enumName + "】不存在");
		}
		for(String value: map.keySet()) {
			if(map.get(value).equals(label)) {
				return value;
			}
		}
		throw new SystemException("枚举内容配置错误：枚举【" + enumName + "】对应【" + label + "】不存在");
	}

	@Override
	public JSONArray getOptions(Field field) {
		JSONArray options = new JSONArray();
		Label label = field.getAnnotation(Label.class);
		if(label != null) {
			String enumContent = label.enumContent();
			for(String id: getEnumContent(enumContent).keySet()) {
				options.add(createOption(id,getEnumContent(enumContent).get(id)));
			}
		}
		return options;
	}

	@Override
	public Object convert(Object currentValue, Object root, Field field) {
		if(currentValue == null) {
			return null;
		}
		Label label = field.getAnnotation(Label.class);
		String newValue = "";
		if(label != null) {
			String enumContent = label.enumContent();
			return convert(currentValue, enumContent, label.multiSelect());
		}
		return newValue;
	}
	public Object convert(Object currentValue, String enumContent, boolean multiSelect) {
		if(currentValue == null) {
			return null;
		}
		String newValue = "";
		if(enumContent.startsWith("join:")) {
			return newValue;
		}
		Map<String, String> enumMap = getEnumContent(enumContent);
		for(String id: enumMap.keySet()) {
			if(multiSelect) {
				for (String optionId: ((String)currentValue).split(",")) {
					if(optionId.equals(id)) {
						newValue += "," + getEnumContent(enumContent).get(id);
					}
				}
			}else {
				newValue = enumMap.get(currentValue.toString());
			}
		}
		if(newValue != null && newValue.length() > 0 && multiSelect) {
			newValue = newValue.substring(1);
		}
		return newValue;
	}
	public Object convert(Object currentValue, String enumContent) {
		return convert(currentValue, enumContent, false);
	}


	@SuppressWarnings("unchecked")
	public BaseServiceImpl getService(String entityName) {
		BaseServiceImpl service = null;
		try {
			service = (BaseServiceImpl) springUtil.getBean(StringUtil.firstLetterLowCase(entityName) + "Service");
		} catch (Exception e) {
			log.error("EnumContentProvider.getService",e);
			service = (BaseServiceImpl) springUtil.getBean(StringUtil.firstLetterLowCase(entityName) + "ServiceImpl");
		}
		return service;
	}
	@SuppressWarnings("unchecked")
	public BaseBean getBeanInstance(String entityName) {
		try {
			return ((Class<BaseBean>) forName(ConstantUtil.BEAN_PACKAGE + "." + entityName)).newInstance();
		} catch (InstantiationException e) {
			log.error("EnumContentProvider.getBeanInstance",e);
		} catch (IllegalAccessException e) {
			log.error("EnumContentProvider.getBeanInstance",e);
		} catch (ClassNotFoundException e) {
			log.error("EnumContentProvider.getBeanInstance",e);
		}
		return null;
	}

	public synchronized void refresh(){
		map.clear();
	}
}
